<template>
      <el-button type="primary" icon="Plus" :disabled="disabled" @click="confirm" >创建试卷</el-button>

      <!-- 模糊查询开始 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-top: 20px">
        <el-form-item label="试卷创建时间">
        <el-date-picker
            v-model="time"
            type="datetimerange"
            start-placeholder="请选择开始时间"
            end-placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
        </el-form-item>
        <el-form-item label="考试名称">
          <el-input  placeholder="请输入考试名称" v-model="formInline.examName" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getExamListAPI">搜索</el-button>
          <el-button @click="reset">清空</el-button>
        </el-form-item>
      </el-form>
      <!-- 模糊查询结束 -->

      <!-- 列表渲染开始 -->
      <el-table ref="multipleTableRef"  style="width: 100%" border :data="examList" >
        <el-table-column property="id" width="100" label="id" align="center" />
        <el-table-column property="examName" width="100" label="考试名称" align="center" />
        <el-table-column  label="班级" width="80" align="center">
          <template v-slot="scope">
            {{ className }}
          </template>
        </el-table-column>
        <el-table-column property="examType" label="考试类型" width="120" align="center" >
        <template v-slot="scope">
          <el-tag v-if="scope.row.examType === 0" type="primary">模拟考试</el-tag>
          <el-tag v-else type="danger">考试</el-tag>
        </template>
        </el-table-column>
        <el-table-column property="status" label="状态"  width="70" align="center">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">未开始</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="primary">进行中</el-tag>
            <el-tag v-else type="danger">已结束</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="createTime" label="试卷创建时间" min-width="173" align="center" />
        <el-table-column property="examStartTime" label="考试开始时间" min-width="173" align="center" />
        <el-table-column property="duration" label="考试时长（分钟）" width="150" align="center" />
        <el-table-column property="examEndTime" label="考试结束时间" min-width="193" align="center" />
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template v-slot="scope">
            <el-link type="primary" icon="edit" style="margin-right: 10px" :disabled="disabled" @click="showUpdate(scope.row.id)" v-show="scope.row.status==0">修改</el-link>
            <el-link type="danger" icon="delete" style="margin-right: 10px" :disabled="disabled" @click="deleteDialogVisible=true;questionId=scope.row.id" v-show="scope.row.status==0">删除</el-link>
            <el-link type="primary" icon="paperclip" :disabled="disabled" @click="releaseDialogVisible=true;questionId=scope.row.id" v-show="scope.row.status==0">发布</el-link>
            <el-link type="primary" icon="EditPen" :disabled="disabled" @click="correctExam(scope.row.id)" v-show="scope.row.status==2">批改试卷</el-link>
            <el-link type="danger"  v-show="scope.row.status==1" disabled>考试正在进行中，无法对它进行操作呦！</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div  style="margin-top: 20px;">
        <el-pagination v-model:current-page="formInline.page" v-model:page-size="formInline.size" :page-sizes="[5, 10, 15, 20]" :total="formInline.total"
                       :background="true" layout="total, sizes, prev, pager, next" @current-change="handleCurrentChange"
                       @size-change="handleSizeChange" />
      </div>
  <!-- 发布二次弹窗确认 -->
  <el-dialog v-model="releaseDialogVisible" title="警告" width="500" center>
    <div style="text-align: center;width:500px">
      这个操作不可逆，请考虑清楚呦！点击之后会立马开始考试
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="releaseDialogVisible = false" type="primary">取消</el-button>
        <el-button type="danger" @click="releaseById()">
          确认发布
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 删除二次弹窗确认 -->
  <el-dialog v-model="deleteDialogVisible" title="警告" width="500" center>
    <div style="text-align: center;width:500px">
      这个操作不可逆，请考虑清楚呦！点击之后会这个考试试卷会被删除
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteDialogVisible = false" type="primary">取消</el-button>
        <el-button type="danger" @click="open()">
          确认删除
        </el-button>
      </div>
    </template>
  </el-dialog>
      <!-- 修改列表渲染结束 -->
  <el-dialog v-model="updateDialogVisible" :title="questionList.examName" width="1000px"  center>
    <el-button type="primary"  @click="updateExam">确认修改</el-button>
    <div v-loading="loading">
    <el-form :inline="true" :model="questionList" class="demo-form-inline" >
      <el-form-item label="考试时间" prop="examStartTime">
       {{questionList.examStartTime}}
      </el-form-item>
      <el-form-item label="考试时长" style="width: 230px" >
        <el-input placeholder="请输入考试时长(分钟)" v-model="questionList.duration" type="number" clearable />
      </el-form-item>
    </el-form>
    <div v-for="(item,index) in questionList.list" v-if="answerList.length>0" >
      <div style="padding: 10px 10px 10px 10px;" v-if="item.questionType==='0'">
        <div>
          {{index+1}}.单选题
          <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
        </div>
        <el-input
            v-model="item.questionTitle"
            style="width: 100%"
            placeholder="请输入题干内容（必填）"
            show-word-limit
            type="textarea"
        />
        <div style="margin-top: 10px">
          <el-radio-group v-model="answerList[index][0]" @change="updateCorrectRadio(item,index)" v-if="item.options.length>0">
            <el-radio value="0">A
              <el-input
                  v-model="item.options[0].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-radio>
            <el-radio value="1">B
              <el-input
                  v-model="item.options[1].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-radio>
            <el-radio value="2">C
              <el-input
                  v-model="item.options[2].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-radio>
            <el-radio value="3">D
              <el-input
                  v-model="item.options[3].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-radio>
          </el-radio-group>
          <div style="margin-top: 20px">
            分数：<el-input-number :min="0" v-model="item.score"  /></div>
        </div>
      </div>
      <div style="padding: 10px 10px 10px 10px;" v-else-if="item.questionType==='1'">
        {{index+1}}.多选题
        <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
        <el-input
            v-model="item.questionTitle"
            style="width: 100%"
            placeholder="请输入题干内容（必填）"
            show-word-limit
            type="textarea"
        />
        <div style="margin-top: 10px">
          <el-checkbox-group v-model="answerList[index]" @change="updateCorrectCheckbox(item,index)" v-if="item.options.length>0">
            <el-checkbox value="0">A
              <el-input
                  v-model="item.options[0].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-checkbox>
            <el-checkbox  value="1" >B
              <el-input
                  v-model="item.options[1].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-checkbox>
            <el-checkbox  value="2" >C
              <el-input
                  v-model="item.options[2].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-checkbox>
            <el-checkbox  value="3">D
              <el-input
                  v-model="item.options[3].optionText"
                  style="width: 280px"
                  placeholder="请输入选项;选中及设置为正确答案（必填）"
                  show-word-limit
                  type="text"
              />
            </el-checkbox>
          </el-checkbox-group>
          <div style="margin-top: 20px">
            分数：<el-input-number :min="0" v-model="item.score"  /></div>
        </div>
      </div>
      <div style="padding: 10px 10px 10px 10px;" v-else-if="item.questionType==='2'">
        {{index+1}}.判断选题
        <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)"/></div>
        <el-input
            v-model="item.questionTitle"
            style="width: 100%"
            placeholder="请输入题干内容（必填）"
            show-word-limit
            type="textarea"
        />
        <div style="margin-top: 10px">
          <el-radio-group v-model="answerList[index][0]" @change="updateCorrectRadio(item,index)" v-if="item.options.length>0">
            <el-radio value="0" >A
              <el-input
                  disabled
                  style="width: 280px"
                  placeholder="正确"
                  show-word-limit
                  type="text"
              />
            </el-radio>
            <el-radio value="1">B
              <el-input
                  disabled
                  style="width: 280px"
                  placeholder="错误"
                  show-word-limit
                  type="text"
              />
            </el-radio>
          </el-radio-group>
          <div style="margin-top: 20px">
            分数：<el-input-number :min="0"  v-model="item.score" /></div>
        </div>
      </div>
      <div style="padding: 10px 10px 10px 10px;" v-else>
        {{index+1}}.主观题
        <div style="float: right;"><Delete style="width: 1.5em; height: 1.5em; margin-right: 8px" @click="deleteQuestion(index)" /></div>
        <el-input
            v-model="item.questionTitle"
            style="width: 100%"
            placeholder="请输入题干内容（必填）"
            show-word-limit
            type="textarea"
        />
        <div style="margin-top: 10px">
          <el-input
              v-model="item.answerContent"
              style="width: 600px"
              placeholder="请输入参考答案（必填）"
              show-word-limit
              type="text"
          />
          <div style="margin-top: 20px">
            分数：<el-input-number :min="0"  v-model="item.score"/></div>
        </div>
      </div>
    </div>
    </div>
  </el-dialog>


</template>
<script lang="ts" setup>
import { onMounted, ref} from 'vue'
import {Action, ElMessage, ElMessageBox, ElTable} from "element-plus";
import axiosInstance from "@/axios/index";
import  router  from "@/router";
import {Delete} from "@element-plus/icons-vue";
import {useStaffStore} from "@/stores/staff.js";

//是否有权限操作
let disabled = !(localStorage.getItem("purview") == "true")
//班级名称
const className=ref(localStorage.getItem("className"))
//创建试卷弹窗控制器
const centerDialogVisible=ref(false)
//修改试卷弹窗控制器
const updateDialogVisible=ref(false)
//发布二次确认状态
const releaseDialogVisible=ref(false)
//删除二次确认
const deleteDialogVisible=ref(false)
//操作题目编码
const questionId=ref()
//筛选时间
const time = ref([])
//模糊查询列表
const formInline = ref({
  examName: '',
  page:1,
  size:5,
  total:0,
  classId:localStorage.getItem("classId")
})
//清除功能.
const reset=()=>{
  time.value=[]
  formInline.value.endTime=''
  formInline.value.startTime=''
  formInline.value.examName=''
}
//删除二次确认
const open = () => {
  deleteExam(questionId.value)
  deleteDialogVisible.value=false
}

//单选答案
const updateCorrectRadio=(item,index)=> {
  item.options.forEach((option) => {
    if (option.isCorrect === 1) {
      option.isCorrect = 0
    }
  })
  item.options[answerList.value[index]].isCorrect = 1
}
//确认多选题目答案
const updateCorrectCheckbox=(item,index)=>{
  item.options.forEach((option) => {
    if (option.isCorrect === 1) {
      option.isCorrect = 0
    }
  })
  for (let i = 0; i < answerList.value[index].length; i++) {
    item.options[answerList.value[index][i]].isCorrect= 1
  }
}
//考试记录列表
const examList = ref([])
//查询考试记录详细信息
const questionList =ref({})
//查询考试记录详细答案信息
const answerList =ref([])
//查询考试记录
const getExamListAPI = () => {
  axiosInstance.get('/examRecords/selectList', {
    params:{
      examStartTime: time.value[0],
      endTime: time.value[1],
      examName: formInline.value.examName,
      current: formInline.value.page,
      size: formInline.value.size,
      classId:formInline.value.classId
    }
  }).then(res => {
      examList.value = res.data.data.records
      formInline.value.total=res.data.data.total
      formInline.value.page=res.data.data.page
      formInline.value.size=res.data.data.size
  })
}

//获取考试记录列表
onMounted(()=>getExamListAPI())

//page发生变化触发
const handleCurrentChange = (val) => {
  getExamListAPI()
}

const handleSizeChange = (val) => {
  getExamListAPI()
}
//删除功能
const deleteExam=(id)=>{
  axiosInstance.post('/examRecords/del',{id:id}).then(res=>{
    if (res.data.code==200){
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      getExamListAPI()
    }else {
      ElMessage({
        message: '删除失败',
        type: 'error',
      })
    }
  }
  )
}
//发布功能
const releaseById=()=>{
  axiosInstance.post('/examRecords/release',{
    id:questionId.value,
    status:1
  }).then(res=>{
    if (res.data.code==200){
      ElMessage({
        message: '发布成功',
        type: 'success',
      })
      releaseDialogVisible.value=false
      getExamListAPI()
    }else {
      ElMessage({
        message: '发布失败',
        type: 'error',
      })
    }
  }
  )
}


//创建考试确认调用方法
const confirm=()=>{
      centerDialogVisible.value = false
     router.push({path: '/classManagement/exam/createExam'})
}
const loading= ref(false)
//修改试卷方法
const showUpdate=(id)=>{
  axiosInstance.get('/examRecords/selectById',{params:{id:id}}).then(res=> {
    questionList.value=res.data.data
    console.log(questionList.value)
    let options=[]
    answerList.value=[]
    for (let i = 0; i < res.data.data.list.length; i++) {
      if(res.data.data.list[i].options.length!==0){
        for (let j = 0; j < res.data.data.list[i].options.length; j++) {
          if (res.data.data.list[i].options[j].isCorrect === 1) {
            options.push(j + '')
          }
        }
        answerList.value.push(options)
        options=[]
      }else {
        answerList.value.push([])
      }
    }
    updateDialogVisible.value=true
  })
}

//删除题目
const deleteQuestion = (index)=>{
  if(questionList.value.list.length<=1){
    ElMessage({
      message: '删除失败,试卷不能删除到没有题目',
      type: 'error',
    })
  }else {
    questionList.value.list.splice(index,1)
    answerList.value.splice(index,1)
  }
}
//修改试卷
const updateExam=()=>{
  loading.value=true
  questionList.value.updateBy=useStaffStore().staffInfo.staff.id
    axiosInstance.post("/examRecords/update",JSON.stringify(questionList.value),{headers:{"Content-Type":"application/json"}}).then(res=>{
      if (res.data.code==200){
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        loading.value=false
        updateDialogVisible.value=false
        getExamListAPI()
      }else {
        ElMessage({
          message: '修改失败',
          type: 'error',
        })
      }
    })
}
//批改试卷
const correctExam=(id)=>{
  router.push({path:'/classManagement/exam/correctExamView',query:{id:id}})
}
</script>

<style>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
